package com.ukefu.webim.web.handler.apps.workorders;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.es.ContactsRepository;
import com.ukefu.webim.service.es.FavoritesRepository;
import com.ukefu.webim.service.es.OrdersCommentRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.impl.WorkOrdersSendMailService;
import com.ukefu.webim.service.repository.DataEventRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.OrgiSkillRelRepository;
import com.ukefu.webim.service.repository.PropertiesEventRepository;
import com.ukefu.webim.service.repository.TagRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.service.repository.WorkOrderTypeRepository;
import com.ukefu.webim.util.PropertiesEventUtils;
import com.ukefu.webim.util.WorkOrdersUtils;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.DataEvent;
import com.ukefu.webim.web.model.Favorites;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.Organ;
import com.ukefu.webim.web.model.OrgiSkillRel;
import com.ukefu.webim.web.model.PropertiesEvent;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.WorkOrderType;
import com.ukefu.webim.web.model.WorkOrders;

import freemarker.template.TemplateException;

@Controller
@RequestMapping("/apps/workordersthree")
public class WorkOrdersForThreeController extends Handler{
	
	@Autowired
	private WorkOrdersRepository workOrdersRes ;
	
	@Autowired
	private OrdersCommentRepository ordersCommentRes ;
	
	@Autowired
	private ContactsRepository contactsRes ;
	
	@Autowired
	private PropertiesEventRepository propertiesEventRes ;
	
	@Autowired
	private DataEventRepository dataEventRes ;
	
	@Autowired
	private TagRepository tagRes ;
	
	@Autowired
	private UserRepository userRes ;
	
	@Autowired
	private OrganRepository organRes ;
//	
//	@Autowired
//	private SnakerEngineFacets facets;
//	
//	@Autowired
//	private MetadataRepository metadataRes ;
	
	@Autowired
	private FavoritesRepository favRes ;
	
	@Autowired
	private WorkOrderTypeRepository workOrderTypeRes ;
	
	@Autowired
	private OrgiSkillRelRepository orgiSkillRelService;
	
	@Autowired
	private WorkOrdersSendMailService workOrdersSendMailService;
	
	@Value("${web.upload-path}")
    private String path;
	
    @RequestMapping("/index")
    @Menu(type = "workorders" , subtype = "index" , access = false)
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	if(!StringUtils.isBlank(ckind)){
    		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
        	map.put("ckind", ckind) ;
        }
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.must(QueryBuilders.matchAllQuery()) ;
    	myBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	Page<WorkOrders> workOrdersNum = workOrdersRes.countById(myBuilder, null  , false , null, 0, 30,null) ;
    	
    	BoolQueryBuilder unclosed = QueryBuilders.boolQuery();
    	unclosed.mustNot(QueryBuilders.termQuery("status", UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	unclosed.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> unclosedOrders = workOrdersRes.countById(unclosed, null  , false , null, 0, 30,null) ;
    	
    	BoolQueryBuilder my = QueryBuilders.boolQuery();
    	my.must(QueryBuilders.termQuery("creater", super.getUser(request).getId())) ;
    	my.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	my.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> myOrders = workOrdersRes.countById(my, null  , false , null, 0, 30,null) ;
    	
    	BoolQueryBuilder workitem = QueryBuilders.boolQuery();
    	workitem.must(QueryBuilders.termQuery("accuser", super.getUser(request).getId())) ;
    	workitem.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	workitem.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> workitemOrders = workOrdersRes.countById(workitem, null , false , null, 0, 30,null) ;
    	
    	
    	
    	BoolQueryBuilder status = QueryBuilders.boolQuery();
//    	status.must(QueryBuilders.termQuery("accuser", super.getUser(request).getId())) ;
    	status.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	status.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> statusOrders = workOrdersRes.countById(status, "status"  , false , null, 0, 30,null) ;
    	
    	
    	BoolQueryBuilder wotype = QueryBuilders.boolQuery();
//    	wotype.must(QueryBuilders.termQuery("accuser", super.getUser(request).getId())) ;
    	wotype.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	wotype.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> wotypeOrders = workOrdersRes.countById(wotype, "wotype"  , false , null, 0, 30,null) ;
    	
    	map.addAttribute("total", workOrdersNum.getTotalElements()) ;
    	map.addAttribute("unclosed", unclosedOrders.getTotalElements()) ;
    	map.addAttribute("my", myOrders.getTotalElements()) ;
    	map.addAttribute("workitem", workitemOrders.getTotalElements()) ;
    	
    	map.addAttribute("statusOrders", statusOrders) ;
    	map.addAttribute("wotypeOrders", wotypeOrders) ;
    	
    	
    	BoolQueryBuilder workItemBoolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder workItemBuilder = QueryBuilders.boolQuery();
    	workItemBuilder.should(termQuery("accuser" , super.getUser(request).getId())) ;
    	workItemBoolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	workItemBoolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	workItemBoolQueryBuilder.must(workItemBuilder) ;
    	
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(workItemBoolQueryBuilder, false  , false , q, super.getUser(request).getId(),  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	
    	map.addAttribute("workOrderTypeList", workOrderTypeRes.findByOrgi(super.getOrgi(request))) ;
    	
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/index"));
    }
    
    public Page<OrdersComment> getCommentList(WorkOrders workOrders , HttpServletRequest request ){
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.must(termQuery("dataid" , workOrders.getId())) ;
    	myBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	
    	boolQueryBuilder.must(myBuilder) ;
    	
    	return ordersCommentRes.findByQuery(boolQueryBuilder, null , new PageRequest(super.getP(request), super.getPs(request)));
    }
    
    
    @RequestMapping("/favorites")
    @Menu(type = "workorders" , subtype = "favorites" , access = false)
    public ModelAndView favorites(ModelMap map , HttpServletRequest request , @Valid String q) {
    	
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, true , false, q, super.getUser(request).getId(),  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	if(page.getContent().size()>0){
    		WorkOrders workOrders = page.getContent().get(0) ;
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    		
    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgiByTenantshare(request)));
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		
    		map.addAttribute("workOrders", workOrders);
    		
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    	}
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/favorites/index"));
    }
    
    @RequestMapping("/favorites/detail")
    @Menu(type = "workorders" , subtype = "favoritesdetail" , access = false)
    public ModelAndView favoritesdetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/favorites/detail"));
    }
    
    @RequestMapping("/favorites/save")
    @Menu(type = "workorders" , subtype = "favoritessave" , access = false)
    public ModelAndView favoritessave(ModelMap map , HttpServletRequest request , @Valid String id ,@Valid OrdersComment comment) throws IOException, TemplateException {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    	if(workOrders!=null && comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
    		comment.setId(UKTools.getUUID());
    		comment.setCreater(super.getUser(request).getId());
    		comment.setOrgi(super.getOrgi(request));
    		if(!StringUtils.isBlank(comment.getDataid())){
    			comment.setDataid(id);
    		}
    		comment.setCreatetime(new Date());
    		ordersCommentRes.save(comment) ;
    		
    		/**
    		 * 数据变更记录
    		 */
    		DataEvent event = new DataEvent();
    		event.setDataid(workOrders.getId());
			event.setCreater(super.getUser(request).getId());
			event.setOrgi(super.getOrgi(request));
			event.setModifyid(UKTools.genID());
			event.setCreatetime(new Date());
        	event.setCreatetime(new Date());
        	event.setName("comment");
        	
        	String text = Jsoup.parse(comment.getContent()).text() ;
        	if(text.length() > 200){
        		event.setContent(text.substring(0, 200));
        	}else if(text.length() > 0){
        		event.setContent(text);
        	}
        	dataEventRes.save(event) ;
        	//变更发送邮件
    		workOrdersSendMailService.sendUpdateWorkOrdersMail(workOrders);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/favorites/detail.html?id="+id));
    }
    /**
     * 我的待办工单列表，通过工作流引擎查找方式获取
     * @param map
     * @param request
     * @param q
     * @return
     */
    /**
    @RequestMapping("/workitem")
    @Menu(type = "workorders" , subtype = "workitem" , access = false)
    public ModelAndView workitem(ModelMap map , HttpServletRequest request , @Valid String q) {
    	Page<WorkItem> wfpage = new Page<WorkItem>(super.getPs(request));
		wfpage.setPageNo(super.getP(request));
		List<WorkItem> workItems = facets.getEngine().query().getWorkItems(wfpage, new QueryFilter().setProcessType(UKDataContext.BpmType.WORKORDERS.toString()).setOperators(new String[]{super.getUser(request).getId() , super.getUser(request).getOrgan()})) ;

		
		if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", organRes.findByOrgi(super.getOrgi(request))) ;
    	List<String> ids = new ArrayList<String>();
    	for(WorkItem item : workItems){
    		ids.add((String) item.getTaskVariableMap().get("id")) ;
    	}
    	if(ids.size()>0){
	    	Iterable<WorkOrders> tempWorkOrders = workOrdersRes.findByIdInAndOrgi(ids,super.getOrgi(request)) ;
	    	Iterator<WorkOrders> iterator = tempWorkOrders.iterator() ;
	    	List<WorkOrders> workOrdersList = new ArrayList<WorkOrders>();
	    	WorkOrders workOrders = null;
	    	if(iterator.hasNext()){
	    		while(iterator.hasNext()){
	    			if(workOrders == null){
	    				workOrdersList.add(workOrders = iterator.next()) ;
	        		}else{
	        			workOrdersList.add(iterator.next()) ;
	        		}
	    		}
	    		
	    		if(!StringUtils.isBlank(workOrders.getAccdept())){
	    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgi(request))) ;
	    		}
	    		WorkOrdersUtils.processWorkOrders(workOrdersList, userRes, contactsRes);
	    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgi(request)));
	    		
	    		if(!StringUtils.isBlank(workOrders.getInitiator())){
	    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator()));
	    		}
	    		
	    		map.addAttribute("workOrders", workOrders);
	    	}
	    	
	    	map.addAttribute("workOrdersList",workOrdersList);
	    	
	    }
    	return request(super.createAppsTempletResponse("/apps/business/workorder/apps/business/workordersthree/ }
    **/
    @RequestMapping("/workitem")
    @Menu(type = "workorders" , subtype = "workitem" , access = false)
    public ModelAndView workitem(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String id) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.should(termQuery("accuser" , super.getUser(request).getId())) ;
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	
    	boolQueryBuilder.must(myBuilder) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId(),  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	if(page.getContent().size()>0){
    		WorkOrders workOrders = page.getContent().get(0) ;
    		if(!StringUtils.isBlank(id)){
    			for(WorkOrders tempWorkOrders : page.getContent()){
    				if(tempWorkOrders.getId().equals(id)){
    					workOrders = tempWorkOrders ; break ; 
    				}
    			}
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    		
    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgiByTenantshare(request)));
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		
    		map.addAttribute("workOrders", workOrders);
    		
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    	}
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/workitem/index"));
    }
    
    @RequestMapping("/workitem/detail")
    @Menu(type = "workorders" , subtype = "detail" , access = false)
    public ModelAndView workitemdetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/workitem/detail"));
    }
    
    @RequestMapping("/workitem/process")
    @Menu(type = "workorders" , subtype = "update" , access = false)
    public ModelAndView workitemprocess(HttpServletRequest request ,@Valid WorkOrders workOrders , @Valid String id ,@Valid OrdersComment comment) throws IOException, TemplateException {
    	WorkOrders tempWorkOrders = workOrdersRes.findByIdAndOrgi(workOrders.getId(),super.getOrgi(request)) ;
    	if(tempWorkOrders!=null){
    		if(comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
	    		comment.setId(UKTools.getUUID());
	    		comment.setCreater(super.getUser(request).getId());
	    		comment.setOrgi(super.getOrgi(request));
	    		if(!StringUtils.isBlank(comment.getDataid())){
	    			comment.setDataid(id);
	    		}
	    		comment.setCreatetime(new Date());
	    		ordersCommentRes.save(comment) ;
	    		
    		}
    		if(!StringUtils.isBlank(workOrders.getAccuser())){
    			workOrders.setAssigned(true);
    		}else{
    			workOrders.setAssigned(false);
    		}
    		List<PropertiesEvent> events = PropertiesEventUtils.processPropertiesModify(request, workOrders , tempWorkOrders , "id" , "orgi" , "creater" ,"createtime" , "updatetime") ;	//记录 数据变更 历史
	    	if(events.size()>0){
	    		
	    		tempWorkOrders.setAccdept(workOrders.getAccdept());
	    		tempWorkOrders.setAccuser(workOrders.getAccuser());
	    		tempWorkOrders.setPriority(workOrders.getPriority());
	    		tempWorkOrders.setStatus(workOrders.getStatus());
	    		tempWorkOrders.setUpdatetime(new Date());
	    		
	    		if(!StringUtils.isBlank(workOrders.getAccuser())){
	    			tempWorkOrders.setAssigned(true);
	    		}else{
	    			tempWorkOrders.setAssigned(false);
	    		}
		    	workOrdersRes.save(tempWorkOrders) ;
		    	
	    		
	    		/**
        		 * 数据变更记录
        		 */
	    		DataEvent dataEvent = new DataEvent();
	    		if(tempWorkOrders.getAccuser()!=null && tempWorkOrders.getAccuser().equals(workOrders.getAccuser())){
            		dataEvent.setEventtype(UKDataContext.WorkOrdersEventType.ACCEPTUSER.toString());
            	}
        		dataEvent.setDataid(workOrders.getId());
    			dataEvent.setCreater(super.getUser(request).getId());
    			dataEvent.setOrgi(super.getOrgi(request));
    			dataEvent.setModifyid(UKTools.genID());
    			dataEvent.setCreatetime(new Date());
            	dataEvent.setCreatetime(new Date());
            	dataEvent.setName("workorders");
            	dataEventRes.save(dataEvent) ;
            	
	    		Date modifytime = new Date();
	    		for(PropertiesEvent event : events){
	    			event.setDataid(workOrders.getId());
	    			event.setCreater(super.getUser(request).getId());
	    			event.setOrgi(super.getOrgi(request));
	    			event.setModifyid(dataEvent.getId());
	    			event.setCreatetime(modifytime);
	    			if(event.getField().equals("content") && !StringUtils.isBlank(comment.getContent())){
	    				String text = Jsoup.parse(comment.getContent()).text() ;
	    				if(text.length() > 200){
	    					event.setNewvalue(text.substring(0, 200));
	    				}else if(text.length() > 0){
	    					event.setNewvalue(text);
	    				}
	    			}
	    		}
	    		propertiesEventRes.save(events) ;
	    		//变更发送邮件
	    		workOrdersSendMailService.sendUpdateWorkOrdersMail(tempWorkOrders);
	    	}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/workitem.html"));
    }
    
    @RequestMapping("/notassigned")
    @Menu(type = "workorders" , subtype = "notassigned" , access = false)
    public ModelAndView notassigned(ModelMap map , HttpServletRequest request , @Valid String q) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(termQuery("assigned" , false)) ;
    	
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	
    	boolQueryBuilder.must(myBuilder) ;
    	
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId(),  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	if(page.getContent().size()>0){
    		WorkOrders workOrders = page.getContent().get(0) ;
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    		
    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgiByTenantshare(request)));
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		
    		map.addAttribute("workOrders", workOrders);
    		
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    	}
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/notassigned/index"));
    }
    
    @RequestMapping("/notassigned/detail")
    @Menu(type = "workorders" , subtype = "notassigneddetail" , access = false)
    public ModelAndView notassigneddetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/notassigned/detail"));
    }
    
    @RequestMapping("/notassigned/process")
    @Menu(type = "workorders" , subtype = "notassigned" , access = false)
    public ModelAndView notassignedprocess(HttpServletRequest request ,@Valid WorkOrders workOrders , @Valid String id ,@Valid OrdersComment comment) throws IOException, TemplateException {
    	WorkOrders tempWorkOrders = workOrdersRes.findByIdAndOrgi(workOrders.getId(),super.getOrgi(request)) ;
    	if(tempWorkOrders!=null){
    		if(comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
	    		comment.setId(UKTools.getUUID());
	    		comment.setCreater(super.getUser(request).getId());
	    		comment.setOrgi(super.getOrgi(request));
	    		if(!StringUtils.isBlank(comment.getDataid())){
	    			comment.setDataid(id);
	    		}
	    		comment.setCreatetime(new Date());
	    		ordersCommentRes.save(comment) ;
	    		
    		}
    		if(!StringUtils.isBlank(workOrders.getAccuser())){
    			workOrders.setAssigned(true);
    		}else{
    			workOrders.setAssigned(false);
    		}
    		List<PropertiesEvent> events = PropertiesEventUtils.processPropertiesModify(request, workOrders , tempWorkOrders , "id" , "orgi" , "creater" ,"createtime" , "updatetime") ;	//记录 数据变更 历史
	    	if(events.size()>0){
	    		
	    		tempWorkOrders.setAccdept(workOrders.getAccdept());
	    		tempWorkOrders.setAccuser(workOrders.getAccuser());
	    		tempWorkOrders.setPriority(workOrders.getPriority());
	    		tempWorkOrders.setStatus(workOrders.getStatus());
	    		tempWorkOrders.setUpdatetime(new Date());

	    		if(!StringUtils.isBlank(workOrders.getAccuser())){
	    			tempWorkOrders.setAssigned(true);
	    		}else{
	    			tempWorkOrders.setAssigned(false);
	    		}
	    		
		    	workOrdersRes.save(tempWorkOrders) ;
	    		/**
        		 * 数据变更记录
        		 */
        		DataEvent dataEvent = new DataEvent();
        		if(tempWorkOrders.getAccuser()!=null && tempWorkOrders.getAccuser().equals(workOrders.getAccuser())){
            		dataEvent.setEventtype(UKDataContext.WorkOrdersEventType.ACCEPTUSER.toString());
            	}
        		dataEvent.setDataid(workOrders.getId());
    			dataEvent.setCreater(super.getUser(request).getId());
    			dataEvent.setOrgi(super.getOrgi(request));
    			dataEvent.setModifyid(UKTools.genID());
    			dataEvent.setCreatetime(new Date());
            	dataEvent.setCreatetime(new Date());
            	dataEvent.setName("workorders");
            	dataEventRes.save(dataEvent) ;
	    		
	    		Date modifytime = new Date();
	    		for(PropertiesEvent event : events){
	    			event.setDataid(workOrders.getId());
	    			event.setCreater(super.getUser(request).getId());
	    			event.setOrgi(super.getOrgi(request));
	    			event.setModifyid(dataEvent.getId());
	    			event.setCreatetime(modifytime);
	    			if(event.getField().equals("content") && !StringUtils.isBlank(comment.getContent())){
	    				String text = Jsoup.parse(comment.getContent()).text() ;
	    				if(text.length() > 200){
	    					event.setNewvalue(text.substring(0, 200));
	    				}else if(text.length() > 0){
	    					event.setNewvalue(text);
	    				}
	    			}
	    		}
	    		propertiesEventRes.save(events) ;
	    		//变更发送邮件
	    		workOrdersSendMailService.sendUpdateWorkOrdersMail(tempWorkOrders);
	    	}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/notassigned.html"));
    }
    
    @RequestMapping("/myorders")
    @Menu(type = "workorders" , subtype = "myorders" , access = false)
    public ModelAndView myorders(ModelMap map , HttpServletRequest request , @Valid String q) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.should(termQuery("creater" , super.getUser(request).getId())) ;
//    	myBuilder.should(termQuery("accuser" , super.getUser(request).getId())) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	
    	boolQueryBuilder.must(myBuilder) ;
    	
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId() ,  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	if(page.getContent().size()>0){
    		WorkOrders workOrders = page.getContent().get(0) ;
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		map.addAttribute("workOrders", workOrders);
    		
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    	}
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/myorders/index"));
    }
    
    @RequestMapping("/closed")
    @Menu(type = "workorders" , subtype = "closedorders" , access = false)
    public ModelAndView closedorders(ModelMap map , HttpServletRequest request , @Valid String q) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	
    	boolQueryBuilder.must(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	boolQueryBuilder.must(myBuilder) ;
    	
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId() ,  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	if(page.getContent().size()>0){
    		WorkOrders workOrders = page.getContent().get(0) ;
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		map.addAttribute("workOrders", workOrders);
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    	}
    	/**
    	 * 统计
    	 */
    	countWorkOrder(map, request);
    	return request(super.createAppsTempletResponse("/apps/business/workordersthree/closed/index"));
    }
    
    @RequestMapping("/closed/detail")
    @Menu(type = "workorders" , subtype = "closeddetail" , access = false)
    public ModelAndView closeddetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/closed/detail"));
    }
    
    
    @RequestMapping("/myorders/detail")
    @Menu(type = "workorders" , subtype = "mydetail" , access = false)
    public ModelAndView mydetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/myorders/detail"));
    }
    
    
    @RequestMapping("/myorders/save")
    @Menu(type = "workorders" , subtype = "favoritessave" , access = false)
    public ModelAndView myorderssave(ModelMap map , HttpServletRequest request , @Valid String id ,@Valid OrdersComment comment) throws IOException, TemplateException {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    	if(workOrders!=null && comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
    		comment.setId(UKTools.getUUID());
    		comment.setCreater(super.getUser(request).getId());
    		comment.setOrgi(super.getOrgi(request));
    		if(!StringUtils.isBlank(comment.getDataid())){
    			comment.setDataid(id);
    		}
    		comment.setCreatetime(new Date());
    		ordersCommentRes.save(comment) ;
    		
    		
    		/**
    		 * 数据变更记录
    		 */
    		DataEvent event = new DataEvent();
    		event.setDataid(workOrders.getId());
			event.setCreater(super.getUser(request).getId());
			event.setOrgi(super.getOrgi(request));
			event.setModifyid(UKTools.genID());
			event.setCreatetime(new Date());
        	event.setCreatetime(new Date());
        	event.setName("comment");
        	String text = Jsoup.parse(comment.getContent()).text() ;
        	if(text.length() > 200){
        		event.setContent(text.substring(0, 200));
        	}else if(text.length() > 0){
        		event.setContent(text);
        	}
        	dataEventRes.save(event) ;
        	//变更发送邮件
    		workOrdersSendMailService.sendUpdateWorkOrdersMail(workOrders);
    	}
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/myorders/detail.html?id="+id));
    }

    @RequestMapping("/edit")
    @Menu(type = "workorders" , subtype = "detail" , access = false)
    public ModelAndView edit(ModelMap map , HttpServletRequest request , @Valid String id) {
    	ModelAndView view = request(super.createAppsTempletResponse("/apps/business/workordersthree/edit"));
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    	if(workOrders!=null && super.getUser(request).getId().equals(workOrders.getCreater())){
    		map.addAttribute("workOrders", workOrders);
    		
    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgiByTenantshare(request)));
    		
    		if(!StringUtils.isBlank(workOrders.getCusid())){
    			workOrders.setContacts(contactsRes.findByIdAndOrgi(workOrders.getCusid(),super.getOrgi(request)));
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    	}else{
    		view = request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/myorders.html"));
    	}
    	map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.WORKORDERS.toString())) ;
    	map.addAttribute("organList", getOrgan(request)) ;
    	
    	map.addAttribute("workOrderTypeList", workOrderTypeRes.findByOrgi(super.getOrgi(request))) ;
    	
    	return view;
    }
    
    @RequestMapping("/add")
    @Menu(type = "workorders" , subtype = "add" , access = false)
    public ModelAndView add(ModelMap map , HttpServletRequest request) {
    	map.addAttribute("userList", getUsers(request)) ;
    	map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.WORKORDERS.toString())) ;
    	map.addAttribute("organList", getOrgan(request)) ;
    	
    	map.addAttribute("workOrderTypeList", workOrderTypeRes.findByOrgi(super.getOrgi(request))) ;
        return request(super.createAppsTempletResponse("/apps/business/workordersthree/add"));
    }
    
    @RequestMapping("/fav/order")
    @Menu(type = "workorders" , subtype = "favorder" , access = false)
    public ModelAndView favorder(ModelMap map , HttpServletRequest request , @Valid Favorites fav) {
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(fav.getOrderid(),super.getOrgi(request)) ;
    	if(!StringUtils.isBlank(fav.getOrderid())){
    		List<Favorites> favList = favRes.findByOrderidAndOrgi(fav.getOrderid() , super.getOrgi(request)) ;
    		if(favList.size() > 0){
    			favRes.delete(favList);
    		}else{
	    		fav.setOrgi(super.getOrgi(request));
	    		fav.setCreater(super.getUser(request).getId());
	    		fav.setCreatetime(new Date());
	    		fav.setModel(UKDataContext.ModelType.WORKORDERS.toString());
	    		fav.setUsername(super.getUser(request).getUsername());
	    		favRes.save(fav) ;
	    		workOrders.setFav(fav);
    		}
    		map.addAttribute("workOrders" , workOrders) ;
    	}
        return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/orderno"));
    }
    
    @RequestMapping("/dept/user")
    @Menu(type = "workorders" , subtype = "deptuser" , access = false)
    public ModelAndView add(ModelMap map , HttpServletRequest request , @Valid String dept) {
    	if(!StringUtils.isBlank(dept)){
    		map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(dept , false , super.getOrgiByTenantshare(request))) ;
    	}
        return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/deptuser"));
    }
    
    @RequestMapping("/save")
    @Menu(type = "workorders" , subtype = "save" , access = false)
    public ModelAndView save(HttpServletRequest request ,@Valid WorkOrders workOrders) throws FileNotFoundException, IOException, TemplateException {
    	
    	workOrders.setOrgi(super.getOrgi(request));
    	workOrders.setCreater(super.getUser(request).getId());
    	workOrders.setUsername(super.getUser(request).getUsername());
    	
    	workOrders.setOrgan(super.getUser(request).getOrgan());


		String orderNo = String.valueOf(WorkOrdersUtils.getWorkOrderNumber(super.getOrgi(request)));
		List<WorkOrders> orderNoList = null;
		do {
			orderNoList	= workOrdersRes.findByOrdernoAndOrgi(orderNo,super.getOrgi(request));
			if(orderNoList != null && orderNoList.size() > 0){
				orderNo = String.valueOf(WorkOrdersUtils.getWorkOrderNumber(super.getOrgi(request)));
			}
		}while (orderNoList != null && orderNoList.size() > 0);


		workOrders.setOrderno(orderNo);

    	if(!StringUtils.isBlank(workOrders.getAccuser())){
    		workOrders.setAssigned(true) ;
    	}else{
    		workOrders.setAssigned(false) ;
    	}
    	
    	WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    	if(workOrderType!=null && workOrderType.isBpm() && !StringUtils.isBlank(workOrderType.getProcessid())){
//    		WorkOrdersUtils.createProcessInstance(facets , workOrderType , super.getUser(request), workOrders , metadataRes.findByTablename(UKDataContext.MetadataTableType.UK_WORKORDERS.toString())) ;
    	}
    	
    	
    	workOrdersRes.save(workOrders) ;
    	//发送工单邮件
    	workOrdersSendMailService.sendCreateWorkOrdersMail(workOrders,super.getUser(request),super.getOrgi(request));
//    	
//    	if(!StringUtils.isBlank(workOrders.getAccuser()) && facets.getEngine().process().getProcessByName(UKDataContext.BpmType.WORKORDERS.toString())!=null){
//    		workOrders.setAssigned(true);
//	    	HashMap<String , Object> args = new HashMap<String , Object>();
//	    	args.put("id", workOrders.getId()) ;
//	    	Order order = facets.startAndExecuteByName(UKDataContext.BpmType.WORKORDERS.toString(), super.getUser(request).getId(), args , workOrders.getAccuser());
//	    	workOrders.setBpmid(order.getId());		//保存 BPMID 和 置状体为 true
//	    	workOrders.setAssigned(true);	
//	    	workOrdersRes.save(workOrders) ;
//    	}else{
//    		workOrders.setAssigned(false);
//    		workOrdersRes.save(workOrders) ;
//    	}
//		workOrders.setAssigned(false);
//		workOrdersRes.save(workOrders) ;

    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/index.html"));
    }
    
    @RequestMapping("/update/all")
    @Menu(type = "workorders" , subtype = "updateall" , access = false)
    public ModelAndView updateall(HttpServletRequest request ,@Valid WorkOrders workOrders) throws IOException, TemplateException {
    	WorkOrders tempWorkOrders = workOrdersRes.findByIdAndOrgi(workOrders.getId(),super.getOrgi(request)) ;
    	if(tempWorkOrders!=null){
    		if(!StringUtils.isBlank(workOrders.getAccuser())){
    			workOrders.setAssigned(true);
    		}else{
    			workOrders.setAssigned(false);
    		}
    		List<PropertiesEvent> events = PropertiesEventUtils.processPropertiesModify(request, workOrders , tempWorkOrders , "id" , "orgi" , "creater" ,"createtime" , "updatetime") ;	//记录 数据变更 历史
	    	if(events.size()>0){
	    		
	    		DataEvent dataEvent = new DataEvent();
	    		if(tempWorkOrders.getAccuser()!=null && tempWorkOrders.getAccuser().equals(workOrders.getAccuser())){
            		dataEvent.setEventtype(UKDataContext.WorkOrdersEventType.ACCEPTUSER.toString());
            	}
        		dataEvent.setDataid(workOrders.getId());
    			dataEvent.setCreater(super.getUser(request).getId());
    			dataEvent.setOrgi(super.getOrgi(request));
    			dataEvent.setModifyid(UKTools.genID());
    			dataEvent.setCreatetime(new Date());
            	dataEvent.setCreatetime(new Date());
            	dataEvent.setName("workorders");
            	dataEventRes.save(dataEvent) ;
	    		
	    		Date modifytime = new Date();
	    		for(PropertiesEvent event : events){
	    			event.setDataid(workOrders.getId());
	    			event.setCreater(super.getUser(request).getId());
	    			event.setOrgi(super.getOrgi(request));
	    			event.setModifyid(dataEvent.getId());
	    			event.setCreatetime(modifytime);
	    		}
	    		propertiesEventRes.save(events) ;
	    	}
    		if(events.size()>0){
    			UKTools.copyProperties(workOrders, tempWorkOrders , "createtime");
    			//变更发送邮件
        		workOrdersSendMailService.sendUpdateWorkOrdersMail(tempWorkOrders);
        		
	    		tempWorkOrders.setUpdatetime(new Date());
		    	workOrdersRes.save(tempWorkOrders) ;
    		}
    	}
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/myorders.html"));
    }
    
    @RequestMapping("/comments")
    @Menu(type = "workorders" , subtype = "comments" , access = false)
    public ModelAndView comments(ModelMap map , HttpServletRequest request , @Valid String orderid) {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(orderid,super.getOrgi(request)) ;
    	if(workOrders!=null){
    		map.addAttribute("orderCommentList", getCommentList(workOrders, request));
    	}
    	map.addAttribute("organList", getOrgan(request)) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/comments"));
    }
    
    @RequestMapping("/detail/comments")
    @Menu(type = "workorders" , subtype = "detailcomments" , access = false)
    public ModelAndView detailcomments(ModelMap map , HttpServletRequest request , @Valid String orderid) {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(orderid,super.getOrgi(request)) ;
    	if(workOrders!=null){
    		map.addAttribute("orderCommentList1", getCommentList(workOrders, request));
    	}
    	map.addAttribute("organList", getOrgan(request)) ;
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/detailcomments"));
    }
    
    @RequestMapping("/detail/dataevent")
    @Menu(type = "workorders" , subtype = "dataevent" , access = false)
    public ModelAndView dataevent(ModelMap map , HttpServletRequest request , @Valid String orderid) {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(orderid,super.getOrgi(request)) ;
    	if(workOrders!=null){
    		map.addAttribute("dataEventList" , dataEventRes.findByDataidAndOrgi(workOrders.getId(), super.getOrgi(request) , new PageRequest(super.getP(request), super.getPs(request)))) ;
    	}
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/detailevent"));
    }
    
    
    @RequestMapping("/pages")
    @Menu(type = "workorders" , subtype = "pages" , access = false)
    public ModelAndView pages(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String tp) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.should(termQuery("accuser" , super.getUser(request).getId())) ;
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	boolQueryBuilder.must(myBuilder) ;
    	
    	if(!StringUtils.isBlank(q)){
        	map.put("q", q) ;
        }
    	if(!StringUtils.isBlank(tp)){
        	map.put("tp", tp) ;
        }
    	map.addAttribute("organList", getOrgan(request)) ;
    	org.springframework.data.domain.Page<WorkOrders> page = workOrdersRes.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId(),  new PageRequest(super.getP(request), super.getPs(request))) ;
    	map.addAttribute("workOrdersList", page);
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/workorderspages"));
    }

    @RequestMapping("/delete")
    @Menu(type = "workorders" , subtype = "delete" , access = false)
    public ModelAndView delete(HttpServletRequest request ,@Valid String id) {
    	WorkOrders tempWorkOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    	tempWorkOrders.setDatastatus(true);
//    	if(tempWorkOrders.isAssigned() && !StringUtils.isBlank(tempWorkOrders.getBpmid())){
//    		facets.getEngine().order().complete(tempWorkOrders.getBpmid());	//结束
//    	}
    	workOrdersRes.save(tempWorkOrders) ;
    	
    	return request(super.createRequestPageTempletResponse("redirect:/apps/workordersthree/myorders.html"));
    }
    
    @RequestMapping("/upload")
    @Menu(type = "workorders" , subtype = "upload" , access = false)
    public ModelAndView upload(HttpServletRequest request , HttpServletResponse response , @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
    	ModelAndView view = request(super.createRequestPageTempletResponse("/apps/business/workordersthree/upload")) ;
    	String imgid = UKTools.getUUID() ;
    	if(file!=null){
	    	FileUtils.writeByteArrayToFile(new File(path , "workorders/"+UKTools.md5(file.getBytes())), file.getBytes());
    	}
    	view.addObject("imgid", imgid) ;
    	view.addObject("name", file.getName()) ;
        return view;
    }
    
    @RequestMapping("/embed/detail")
    @Menu(type = "workorders" , subtype = "embeddetail" , access = false)
    public ModelAndView embeddetail(ModelMap map , HttpServletRequest request , @Valid String id) {
    	workOrderDetail(map, request, id);
    	return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/embed/detail"));
    }
    @RequestMapping("/embed/add")
    @Menu(type = "workorders" , subtype = "add" , access = false)
    public ModelAndView embedadd(ModelMap map , HttpServletRequest request , @Valid String contactsid) {
    	map.addAttribute("userList", getUsers(request)) ;
    	map.addAttribute("tags", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.WORKORDERS.toString())) ;
    	map.addAttribute("organList", getOrgan(request)) ;
    	
    	if(!StringUtils.isBlank(contactsid)){
    		map.addAttribute ("contacts", contactsRes.findByIdAndOrgi(contactsid,super.getOrgi(request)));
		}
    	map.addAttribute("workOrderTypeList", workOrderTypeRes.findByOrgi(super.getOrgi(request))) ;
    	
        return request(super.createRequestPageTempletResponse("/apps/business/workordersthree/embed/add"));
    }
    
    @RequestMapping("/embed/save")
    @Menu(type = "workorders" , subtype = "embedsave" , access = false)
    public ModelAndView embedsave(HttpServletRequest request ,@Valid WorkOrders workOrders , @Valid String contactsid) throws FileNotFoundException, IOException {
    	
    	workOrders.setOrgi(super.getOrgi(request));
    	workOrders.setCreater(super.getUser(request).getId());
    	workOrders.setUsername(super.getUser(request).getUsername());
    	
    	workOrders.setOrgan(super.getUser(request).getOrgan());
    	
    	workOrders.setOrderno(String.valueOf(WorkOrdersUtils.getWorkOrderNumber(super.getOrgi(request))));
    	if(!StringUtils.isBlank(workOrders.getAccuser())){
    		workOrders.setAssigned(true) ;
    	}else{
    		workOrders.setAssigned(false) ;
    	}
    	workOrdersRes.save(workOrders) ;
    	return request(super.createRequestPageTempletResponse("redirect:/agent/workorders/list.html?contactsid="+contactsid));
    }
    /**
     * 统一查询 工单详情
     * @param map
     * @param request
     * @param id
     */
    public void workOrderDetail(ModelMap map , HttpServletRequest request , String id) {
    	
    	WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
    	if(workOrders!=null){
    		map.addAttribute("workOrders", workOrders);
    		
    		if(!StringUtils.isBlank(workOrders.getWotype())){
    			WorkOrderType workOrderType = workOrderTypeRes.findByIdAndOrgi(workOrders.getWotype(), super.getOrgi(request)) ;
    			map.addAttribute("workOrderType", workOrderType);
    		}
    		
    		workOrders.setUser(userRes.findByIdAndOrgi(workOrders.getCreater() , super.getOrgiByTenantshare(request)));
    		
    		if(!StringUtils.isBlank(workOrders.getCusid())){
    			workOrders.setContacts(contactsRes.findByIdAndOrgi(workOrders.getCusid(),super.getOrgi(request)));
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getInitiator())){
    			map.addAttribute("initiator", userRes.findByIdAndOrgi(workOrders.getInitiator(),super.getOrgi(request)));
    		}
    		
    		if(!StringUtils.isBlank(workOrders.getAccdept())){
    			map.addAttribute("userList", userRes.findByOrganAndDatastatusAndOrgi(workOrders.getAccdept() , false , super.getOrgiByTenantshare(request))) ;
    		}
    	}
    	map.addAttribute("workOrderTypeList", workOrderTypeRes.findByOrgi(super.getOrgi(request))) ;
    	map.addAttribute("organList", getOrgan(request)) ;
    	
    	countWorkOrder(map, request);
    }
    /**
     * 统计数据
     * @param map
     * @param request
     * @param id
     */
    public void countWorkOrder(ModelMap map , HttpServletRequest request) {
    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	myBuilder.must(termQuery("creater" , super.getUser(request).getId())) ;
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request)));
    	boolQueryBuilder.must(myBuilder) ;
    	
    	Page<WorkOrders> my = workOrdersRes.countById(boolQueryBuilder, null, false, null , 1, super.getPs(request),null) ;
    	
    	boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	myBuilder = QueryBuilders.boolQuery();
    	myBuilder.must(termQuery("accuser" , super.getUser(request).getId())) ;
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	boolQueryBuilder.must(myBuilder) ;
    	   	
    	Page<WorkOrders> waite = workOrdersRes.countById(boolQueryBuilder, null, false, null , 1, super.getPs(request),null) ;
    	
    	
    	boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	myBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(termQuery("assigned" , false)) ;
    	
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	boolQueryBuilder.must(myBuilder) ;
    	
    	Page<WorkOrders> notassigned = workOrdersRes.countById(boolQueryBuilder, null, false, null , 1, super.getPs(request),null) ;
    	
    	boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	Page<WorkOrders> fav = workOrdersRes.findByCreater(boolQueryBuilder, true , false, null, super.getUser(request).getId(),  new PageRequest(1, super.getPs(request))) ;
 
    	boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	myBuilder = QueryBuilders.boolQuery();
    	
    	boolQueryBuilder.must(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	boolQueryBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
    	boolQueryBuilder.must(myBuilder) ;
    	Page<WorkOrders> closed = workOrdersRes.countById(boolQueryBuilder, null, false, null , 1, super.getPs(request),null) ;
    	
    	map.addAttribute("mycount", my.getTotalElements()) ;
    	map.addAttribute("wait", waite.getTotalElements()) ;
    	map.addAttribute("notassigned", notassigned.getTotalElements()) ;
    	map.addAttribute("fav", fav.getTotalElements()) ;
    	map.addAttribute("closed", closed.getTotalElements()) ;
    }
    private List<Organ> getOrgan(HttpServletRequest request){
    	List<Organ> list = null;
    	if(super.isTenantshare()) {
			List<String> organIdList = new ArrayList<>();
			List<OrgiSkillRel> orgiSkillRelList = orgiSkillRelService.findByOrgi(super.getOrgi(request)) ;
			if(!orgiSkillRelList.isEmpty()) {
				for(OrgiSkillRel rel:orgiSkillRelList) {
					organIdList.add(rel.getSkillid());
				}
			}
			list = organRes.findByIdInAndOrgi(organIdList,super.getOrgi(request));
		}else {
			list = organRes.findByOrgiAndOrgid(super.getOrgi(request),super.getOrgid(request)) ;
		}
    	return list;
    }
    private Page<User> getUsers(HttpServletRequest request){
    	Page<User> list = null;
    	if(super.isTenantshare()) {
			List<String> organIdList = new ArrayList<>();
			List<OrgiSkillRel> orgiSkillRelList = orgiSkillRelService.findByOrgi(super.getOrgi(request)) ;
			if(!orgiSkillRelList.isEmpty()) {
				for(OrgiSkillRel rel:orgiSkillRelList) {
					organIdList.add(rel.getSkillid());
				}
			}
			list = userRes.findByOrganInAndDatastatusAndOrgi(organIdList,false,super.getOrgi(request), new PageRequest(0, 10));
		}else {
			list = userRes.findByOrgiAndDatastatus(super.getOrgi(request),false, new PageRequest(0, 10)) ;
		}
    	return list;
    }
}